<?php

namespace App\Console\Commands\Tools\Camera;

use App\Kuafu\Shop\Enum\CodeEnum;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\Shop\Service\CameraService;
use App\Kuafu\Shop\Service\DeviceCameraService;
use Illuminate\Console\Command;

class BatchCameraStatus extends Command
{
    protected $signature = 'tools:batch-camera-status {shopCode?}';

    protected $description = '批量获取摄像头状态并更新到表';

    public function handle()
    {

        $shopCode = (int)$this->argument('shopCode');
        if (!$shopCode && (config('app.env') == 'dev' || config('app.env') == 'qa')) {
            dump('测试环境只支持单个门店更新');
            return;
        }

        Shop::query()
            ->with(['shopArchivesRel'])
//            ->whereIn('shopCode', [1, 2358])
            ->when($shopCode, function ($query) use ($shopCode) {
                $query->where('shopCode', $shopCode);
            })
            ->whereIn('status', [CodeEnum::SHOP_STATUS_NORMAL, CodeEnum::SHOP_STATUS_PREPARE])
            ->select(['id', 'name', 'shopCode'])
            ->chunkById(100, function ($shops) {
                foreach ($shops as $shopInfo) {
                    $list = CameraService::getCameraList($shopInfo->id, 0);

                    DeviceCameraService::updateCameraStatus($list->toArray(), $shopInfo->id,
                        $shopInfo->shopArchivesRel->cameraStatus ?? 0);// 更新摄像头状态

                    $this->info($shopInfo->id . ':' . $shopInfo->name . '摄像头状态获取完成');
                }

                sleep(1);// 防止请求过多
            });

    }


}
